package com.qezhhnjy.leetcode.question.tree;

import com.qezhhnjy.leetcode.entity.TreeNode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * @author qezhhnjy
 * @date 2020/12/20-19:11
 * 从上到下按层打印二叉树，同一层的节点按从左到右的顺序打印，每一层打印到一行。
 * 给定二叉树: [3,9,20,null,null,15,7],
 * <p>
 * 3
 * / \
 * 9  20
 * /  \
 * 15   7
 * 返回其层次遍历结果：
 * <p>
 * [
 * [3],
 * [9,20],
 * [15,7]
 * ]
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof
 */
public class LevelExportBinaryTree {

    public List<List<Integer>> result = new ArrayList<>();

    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) return result;
        LinkedList<TreeNode> level = new LinkedList<>();
        level.add(root);
        while (!level.isEmpty()) {
            int size = level.size();
            List<Integer> temp = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode poll = level.poll();
                temp.add(poll.val);
                if (poll.left != null) level.add(poll.left);
                if (poll.right != null) level.add(poll.right);
            }
            result.add(temp);
        }
        return result;
    }

    public List<List<Integer>> depth(TreeNode root) {
        if (root == null) return result;
        dfs(root, 0);
        return result;
    }

    private void dfs(TreeNode root, int i) {
        if (root == null) return;
        if (result.size() == i) {
            result.add(new ArrayList<>());
        }
        result.get(i).add(root.val);
        dfs(root.left, i + 1);
        dfs(root.right, i + 1);
    }
}
